package com.jiangtai.smartbox.ui

import android.content.ContentValues
import android.os.Handler
import android.support.v7.widget.GridLayoutManager
import android.util.Log
import com.hjq.toast.ToastUtils
import com.jiangtai.smartbox.R
import com.jiangtai.smartbox.adapter.BoxAdapter
import com.jiangtai.smartbox.base.BaseActivity
import com.jiangtai.smartbox.bean.BoxBean
import com.jiangtai.smartbox.constant.Constant
import com.jiangtai.smartbox.event.SearchBoxEvent
import com.jiangtai.smartbox.service.MyService
import com.jiangtai.smartbox.util.Preference
import dismissLoading
import kotlinx.android.synthetic.main.activity_check_box.*
import org.greenrobot.eventbus.EventBus
import org.litepal.LitePal
import showLoading

/**
 * Created by heCunCun on 2021/5/20
 */
class BoxCheckActivity : BaseActivity() {
//    private var mSerial: Serial? = null
//    private var mOutputStream: OutputStream? = null
//    private var mInputStream: InputStream? = null
//    private var readThread: BoxCheckActivity.ReadThread? = null
    private var list = mutableListOf<BoxBean>()
    private var watchNum: Int by Preference(Constant.WATCH_NUM, 0)//表的数量
    private var updateTime: Long by Preference(Constant.UPDATE_TIME, 0L)//最近盘存时间

    companion object{
        val  TAG = "BoxCheckActivity"
    }
    override fun attachLayoutRes(): Int = R.layout.activity_check_box

    private val mAdapter by lazy {
        BoxAdapter()
    }

    override fun initData() {
        list = LitePal.findAll(BoxBean::class.java)
        rv_box.adapter = mAdapter
        mAdapter.setNewData(list)
        tv_watch_num.text = watchNum.toString()
        tv_empty_num.text = (72 - watchNum).toString()

    }

    override fun initView() {
        rv_box.layoutManager = GridLayoutManager(this, 7)
        //初始化串口
      //  initSerial()
    }

//    private fun initSerial() {
//        val ret = PosUtil.setRs485Status(0)//接收模式
//        if (ret == 0) {
//            Log.e("sb", "切换接收模式成功")
//
//        } else {
//            Log.e("sb", "切换接收模式失败")
//        }
//        try {
//            if (mSerial == null) {
//                mSerial = Serial("/dev/ttyHSL3", 115200, 0)
//            }
//            if (mOutputStream == null) {
//                mOutputStream = mSerial!!.outputStream
//            }
//            if (mInputStream == null) {
//                mInputStream = mSerial!!.inputStream
//            }
//            if (readThread == null) {
//                readThread = ReadThread()
//                readThread!!.start()
//            }
//        } catch (e: java.lang.Exception) {
//            e.printStackTrace()
//        }
//
//    }
//
//    private fun destroySerial() { //释放资源
//        try {
//            if (readThread != null) {
//                readThread!!.interrupt()
//                readThread = null
//            }
//            if (mOutputStream != null) {
//                mOutputStream!!.close()
//                mOutputStream = null
//            }
//            if (mInputStream != null) {
//                mInputStream!!.close()
//                mInputStream = null
//            }
//            if (mSerial != null) {
//                mSerial!!.close()
//                mSerial = null
//            }
//        } catch (e: java.lang.Exception) {
//            e.printStackTrace()
//        }
//    }

//    private fun sendData(data: ByteArray) { //发送命令 data
//        try {
//            if (mOutputStream != null) {
//                mOutputStream!!.write(data)
//                Log.e("send", "sendData = ${HexUtil.formatHexString(data, true)}")
//            }
//        } catch (e: Exception) {
//            e.printStackTrace()
//        }
//    }
//
//    override fun onDestroy() {
//        super.onDestroy()
//        destroySerial()
//    }

    // private var count = 0
//    inner class ReadThread : Thread() {
//        override fun run() {
//            super.run()
//            while (!isInterrupted) {
//                var size = 0
//                try {
//                    var buffer: ByteArray? = ByteArray(1024)
//                    if (mInputStream != null) {
//                        size = mInputStream!!.read(buffer)
//                    }
//                    buffer = Arrays.copyOfRange(buffer, 0, size)
//                    val formatHexString = HexUtil.formatHexString(buffer, true)
//                    Log.e(TAG, "接收数据==$formatHexString,buffer.size={${buffer.size}}")
//                    if (buffer.size==10){
//                        val checkIndex = buffer[2].toInt()
//                        var boxId = ""
//                        if (checkIndex < 10) {
//                            boxId = "0$checkIndex"
//                        } else {
//                            boxId = "$checkIndex"
//                        }
//                        Log.e(TAG, "boxId = $boxId")
//                        val boxs = LitePal.where("boxId = ?", boxId).find(BoxBean::class.java)
//                        if (boxs.isNotEmpty()) {
//                            val boxBean = boxs[0]
//                            boxBean.isChecked = true
//                            boxBean.save()
//                        }
//                    }
//                    if (buffer.size > 12) {
//                        //有表数据返回,直接将表柜状态改成有
//                        if (buffer[10] == 0X12.toByte() && buffer[11] == 0X34.toByte()) {
//                            val index = buffer[2].toInt()
//                            var boxId = ""
//                            if (index < 10) {
//                                boxId = "0$index"
//                            } else {
//                                boxId = "$index"
//                            }
//                            Log.e(TAG, "boxId = $boxId")
//                            val boxs = LitePal.where("boxId = ?", boxId).find(BoxBean::class.java)
//                            if (boxs.isNotEmpty()) {
//                                val boxBean = boxs[0]
//                                boxBean.empty = false
//                                boxBean.save()
//                            }
//
//                        }
//                    }
//
//                } catch (e: IOException) {
//                    e.printStackTrace()
//                }
//            }
//        }
//    }


    private var isChecking = false
    override fun initListener() {
        iv_open_check.setOnClickListener {
            //一键盘点
            showLoading()
            //   count = 0
            list.forEach {
                it.empty = true
            }
            mAdapter.notifyDataSetChanged()
            val contentValues = ContentValues()
            contentValues.put("empty", true)
            contentValues.put("isChecked", false)
            LitePal.updateAll(BoxBean::class.java, contentValues, "empty=?", "0")
            LitePal.updateAll(BoxBean::class.java, contentValues, "isChecked=?", "1")
            Log.e("tt", "isChecking = $isChecking")
            MyService.countWatch=0
            MyService.countBox = 0
            Thread {
                isChecking = true
                while (isChecking) {
                    for (box in list) {
                        if (box.useful) {
//                            if (box.id%2==0L){
//                                val temp = list[0]
//                                EventBus.getDefault().post(SearchBoxEvent(temp))
//                            }else{
//                                val temp = list[1]
//                                EventBus.getDefault().post(SearchBoxEvent(temp))
//                            }
                            EventBus.getDefault().post(SearchBoxEvent(box))
                            Thread.sleep(50)
                        }
                    }
                    isChecking = false

                        handler.postDelayed(Runnable {
                            val watchList = LitePal.where("empty = ?", "0").find(BoxBean::class.java)
                            Log.e(
                                "Watch",
                                "watchNum = ${watchList.size},EmptyNum = ${72 - watchList.size}"
                            )
                            watchNum = watchList.size
                            //记录当前时间   每次间隔2个小时盘存一次
                            updateTime = System.currentTimeMillis()
                            tv_watch_num.text = watchNum.toString()
                            tv_empty_num.text = (72 - watchNum).toString()
                            list= LitePal.findAll(BoxBean::class.java)
                            mAdapter.setNewData(list)
                            Log.e("Thread","threat =${Thread.currentThread().name}")
                            dismissLoading()
                        },12000)


                }

            }.start()

        }

        mAdapter.setOnItemClickListener { adapter, view, position ->
            val boxBean = adapter.data[position] as BoxBean
            //boxBean.isChecked = true
           // mAdapter.notifyItemChanged(position)
            ToastUtils.show("检测${boxBean.boxId}号柜,表的状态")
            //searchWatch(boxBean)
            EventBus.getDefault().post(SearchBoxEvent(boxBean))
            handler.postDelayed(Runnable {
                list = LitePal.findAll(BoxBean::class.java)
                mAdapter.setNewData(list)
            },200)
        }
    }
    private val handler = Handler()
//    private fun searchWatch(boxBean: BoxBean) {
//        val ret = PosUtil.setRs485Status(1)//切换成发送模式
//        if (ret == 0) {
//            Log.e("sb", "切换发送模式成功(查柜表状态),boxBeanId=${boxBean.boxId}")
//        } else {
//            Log.e("sb", "切换发送模式失败,personId=${boxBean.boxId}")
//        }
//        val bytes1 = byteArrayOf(
//            0xAB.toByte(),//帧头
//            0xBA.toByte(),//帧头
//            boxBean.boxId.toByte(),//addr
//            0x08.toByte(),//无应答
//            0x00.toByte(),//无应答
//            0x03.toByte(),//CMD 任意
//            0x04.toByte(),//data length
//            0x00.toByte(),//data length
//            0xAA.toByte(),
//            0x00.toByte(),
//            0X12.toByte(),
//            0X34.toByte(),
//            0xA8.toByte(),//crc
//            0x71.toByte()//crc
//        )
//        Log.e("sb", "crc = ${HexUtil.getCRC(bytes1.copyOfRange(2, 12))}")
//        val bytesCrc = HexUtil.hexStringToByteArray(HexUtil.getCRC(bytes1.copyOfRange(2, 12)))
//        bytes1[12] = bytesCrc[0]
//        bytes1[13] = bytesCrc[1]
//        sendData(bytes1)
//        val state = PosUtil.setRs485Status(0)
//        if (state == 0) {
//            Log.e("sb", "切换发送模式成功")
//        }
//    }
}